package ICM.client;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import java.awt.BorderLayout;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.DropMode;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//import java.io.IOException;
import java.sql.SQLException;
import java.util.Observable;
import java.util.Observer;



import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.border.EtchedBorder;
import javax.swing.JButton;

import common.CommandMessage;
import common.FileUpload;
import common.Request;
import common.TextMessage;
import common.User;

import ICM.server.UserManager;
import javax.swing.ImageIcon;
import com.jgoodies.forms.factories.DefaultComponentFactory;

public class CreateChangeRequestUI extends JPanel implements ActionListener,Observer {
	
	
	private JButton btnsend;
	private JButton btncancel;
	private JTextArea textDescription;
	private JTextArea textComments;
	private JTextArea textReason;
	private JTextField textFileName;
	private JComboBox Department;
	private Client c;
	private ClientUI ui;
	private JTextField textField;
	private boolean Result = false;
	private JFileChooser filechooser;
	private FileUpload fileupload = new FileUpload();

	
	public CreateChangeRequestUI(final Client c, final ClientUI ui) {
		
	this.c=c;
	this.ui=ui;
	setLayout(null);
	c.addObserver(this);
		
		setBackground(Color.LIGHT_GRAY);
		setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		setLayout(null);
		
		Department = new JComboBox();
		Department.setModel(new DefaultComboBoxModel(new String[] {"","Information System", "Moodle", "Library System", "Computer class", "College Website"}));
		Department.setBounds(351, 55, 223, 20);
		add(Department);
		
		JLabel lblNewLabel = new JLabel("Department");
		lblNewLabel.setBounds(119, 58, 196, 14);
		add(lblNewLabel);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(351, 86, 223, 65);
		add(scrollPane);
		
		textDescription = new JTextArea();
		textDescription.setRows(5);
		scrollPane.setViewportView(textDescription);
		
		JLabel lblNewLabel_1 = new JLabel("Description of current situation");
		lblNewLabel_1.setBounds(119, 83, 196, 14);
		add(lblNewLabel_1);
		
		btncancel = new JButton("Cancel" ,new ImageIcon(CreateChangeRequestUI.class.getResource("/client/images/Cancel.png")));
		btncancel.setBounds(366, 396, 125, 35);
		btncancel.addActionListener(this);
		add(btncancel);
		
		JScrollPane scrollPane_1 = new JScrollPane();
		scrollPane_1.setBounds(351, 162, 223, 65);
		add(scrollPane_1);
		
		textReason = new JTextArea();
		scrollPane_1.setViewportView(textReason);
		textReason.setRows(5);
		
		JLabel lblNewLabel_3 = new JLabel("Reason for the request");
		lblNewLabel_3.setBounds(119, 175, 196, 14);
		add(lblNewLabel_3);
		
		textFileName = new JTextField();
		textFileName.setBounds(262, 340, 212, 20);
		add(textFileName);
		textFileName.setColumns(10);
		
		filechooser = new JFileChooser();
		
		JButton btnNewButton = new JButton("Browse...",new ImageIcon(CreateChangeRequestUI.class.getResource("/client/images/browse.png")) );
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				int returnVal = filechooser.showOpenDialog(CreateChangeRequestUI.this);
				 
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = filechooser.getSelectedFile();
	                textFileName.setText(file.getName());
	                String Extension = "";

	                int i = file.getName().lastIndexOf('.');
	                if (i > 0) {
	                    Extension = file.getName().substring(i+1);
	                }
	                
	          	    byte [] fileData = new byte[(int)file.length()];
	          	    FileInputStream d = null;
	          	    try {	          		
		          		d = new FileInputStream(file);
		          		DataInputStream dis = new DataInputStream (d);
		          		dis.readFully(fileData);
		          		dis.close();
		          	} catch (FileNotFoundException e1) {
		          		e1.printStackTrace();
		          	}
	          	   
	          	   catch (IOException e1) {
	          		e1.printStackTrace();
	          	   }
	                fileupload = new FileUpload(file.getName(), (int)file.length(), fileData, Extension);
	            } 
			}
		});
		
		btnNewButton.setBounds(500, 327, 139, 46);
		add(btnNewButton);
		
		btnsend = new JButton("Send" ,new ImageIcon(CreateChangeRequestUI.class.getResource("/client/images/check.png")));
		btnsend.setBounds(201, 396, 125, 35);
		btnsend.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				try {
					String dep = Department.getSelectedItem().toString();
					String desc=textDescription.getText().trim();
					String Reas=textReason.getText().trim();
					String Com=textComments.getText().trim();
					//String FileName=textFileName.getText().trim();
					if(dep.length()<1 || desc.length() < 1  ){
						ClientUI.ShowMessageBox("Error", "Please fill all fields!", JOptionPane.ERROR_MESSAGE);
						return;}
					CommandMessage msg = new CommandMessage("Add request",new Object[] {dep, Integer.toString(ui.getUser().getId()), desc, Com, Reas, fileupload});
					try {
						c.sendToServer(msg);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
					    Thread.sleep(1000);
					} catch(InterruptedException ex) {
					    Thread.currentThread().interrupt();
					}
					
					if (Result)
						ui.ShowMessageBox("Information", "Request created" ,JOptionPane.INFORMATION_MESSAGE);
					else
						ui.ShowMessageBox("Error", "Can't create request" ,JOptionPane.ERROR_MESSAGE);
					ui.SetContent(ui.Main_Screen);
				}
				
						 catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						} 
	
		}});
		add(btnsend);
		
		JLabel lblNewLabel_4 = new JLabel("Additional documents");
		lblNewLabel_4.setBounds(119, 325, 125, 14);
		add(lblNewLabel_4);
		
		JScrollPane scrollPane_3 = new JScrollPane();
		scrollPane_3.setBounds(351, 252, 223, 59);
		add(scrollPane_3);
		
		textComments = new JTextArea();
		textComments.setRows(5);
		scrollPane_3.setViewportView(textComments);
		
		JLabel lblNewLabel_5 = new JLabel("Comments");
		lblNewLabel_5.setBounds(119, 253, 125, 14);
		add(lblNewLabel_5);
		
		JLabel lblPleaseFillThe = DefaultComponentFactory.getInstance().createLabel("Please fill the fields to send request");
		lblPleaseFillThe.setIcon(null);
		lblPleaseFillThe.setBounds(222, 11, 243, 33);
		add(lblPleaseFillThe);
	}


	@Override
	public void actionPerformed(ActionEvent e) {
			if(e.getSource().equals(btncancel)) {
				
					try {
						ui.SetContent(ClientUI.Main_Screen);
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				
			
			}
		
	
		
}

	/**
	 * Handle massage from Observable class in our case Client
	 */
	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
				String msg = "";
				String cmd = "";
				if (arg instanceof TextMessage)
					msg = ((TextMessage)arg).ToDebugMessage();
				else if (arg instanceof CommandMessage) {
					CommandMessage ms=(CommandMessage)arg;
					if(ms.getCommand().equals("Request added"))
						{
							Result = Boolean.parseBoolean(ms.getParams()[1].toString());
						}
				}
				else
					msg = arg.toString();
			}
		
	
}